package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Validated // 参数校验
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,18}$") String password) {
        return userService.register(username, password);
    }

    @PostMapping("login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,18}$") String password) {
        return userService.login(username, password);
    }

    @GetMapping("userInfo")
    public Result userInfo(HttpServletRequest request) {
        return userService.userInfo(request);
    }

    @PutMapping("update")
    public Result update(@RequestBody User user) {
        user.setUpdateTime(LocalDateTime.now());
        boolean b = userService.updateById(user);
        return Result.success(b);
    }

    /**
     * 更新头像
     * @param avatarUrl 图片地址
     * @return 返回结果
     */
    @PatchMapping("updateAvatar")
    public Result updateAvatar(@RequestParam String avatarUrl, HttpServletRequest request) {
        return userService.updateAvatar(avatarUrl, request);
    }

    @PatchMapping("updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params,  @RequestHeader("Authorization") String token) {
        return userService.updatePwd(params, token);
    }
}


